<template>
  <!-- 太阳系容器 - 完全独立，不影响主体布局 -->
  <div 
    v-if="isVisible" 
    ref="container" 
    class="solar-system-container"
    :class="containerClass"
  >
    <!-- 太阳系3D模型将在这里渲染 -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'

// Props - 配置化参数
const props = defineProps({
  // 是否显示太阳系
  visible: {
    type: Boolean,
    default: true
  },
  // 容器样式类
  containerClass: {
    type: String,
    default: ''
  },
  // 太阳系尺寸
  size: {
    type: Number,
    default: 80
  },
  // 是否启用动画
  enableAnimation: {
    type: Boolean,
    default: true
  }
})

// Emits - 事件通知
const emit = defineEmits(['ready', 'error'])

// 响应式数据
const container = ref(null)
const solarSystemSettings = ref({
  enableSolarSystem: true,
  solarSystemSize: 'medium',
  solarSystemPosition: 'title-right',
  autoPauseRendering: true,
  renderQuality: 'medium'
})

// 计算是否显示太阳系
const isVisible = computed(() => {
  // 首先检查props.visible
  if (!props.visible) return false
  
  // 然后检查localStorage中的设置
  if (process.client) {
    try {
      const savedSettings = localStorage.getItem('solarSystemSettings')
      if (savedSettings) {
        const settings = JSON.parse(savedSettings)
        return settings.enableSolarSystem !== false // 默认启用，只有明确设置为false才禁用
      }
    } catch (error) {
      console.error('读取太阳系设置失败:', error)
    }
  }
  
  return true // 默认显示
})

// Three.js 相关变量
let scene, camera, renderer, animationId
let sun, planets = []

// 行星数据配置 - 根据真实行星特征设置颜色
const planetData = [
  { 
    size: 0.6, 
    distance: 2, 
    speed: 0.02, 
    color: 0xFFD700, // 金星 - 金黄色，因为被厚厚的大气层覆盖，呈现金黄色
    tilt: 0.2, 
    name: '金星' 
  },
  { 
    size: 0.8, 
    distance: 4, 
    speed: 0.015, 
    color: 0x4A90E2, // 地球 - 蓝色，代表海洋和大气
    tilt: 0.15, 
    name: '地球' 
  },
  { 
    size: 0.5, 
    distance: 6, 
    speed: 0.012, 
    color: 0xCD5C5C, // 火星 - 红色，因为表面富含氧化铁
    tilt: 0.25, 
    name: '火星' 
  },
  { 
    size: 1.0, 
    distance: 8, 
    speed: 0.008, 
    color: 0xD4AF37, // 木星 - 黄褐色，大气层中的氨和甲烷
    tilt: 0.3, 
    name: '木星' 
  },
  { 
    size: 0.7, 
    distance: 10, 
    speed: 0.005, 
    color: 0xF4A460, // 土星 - 淡橙色，大气层中的氨冰和氢
    tilt: 0.2, 
    name: '土星' 
  }
]

// 初始化 Three.js 场景
const initThreeJS = async () => {
  try {
    if (!container.value) {
      throw new Error('Container not found')
    }

    // 动态导入 Three.js
    const THREE = await import('three')
    
    // 创建场景
    scene = new THREE.Scene()
    
    // 创建相机 - 倾斜的3D视角，适应80×80空间，视野更宽
    camera = new THREE.PerspectiveCamera(85, 1, 0.1, 1000)
    camera.position.set(9, 6, 13) // 相机位置平衡，避免透视畸变
    camera.lookAt(0, 0, 0)
    
    // 创建渲染器
    renderer = new THREE.WebGLRenderer({ 
      alpha: true, 
      antialias: true 
    })
    renderer.setSize(props.size, props.size)
    renderer.setClearColor(0x000000, 0)
    container.value.appendChild(renderer.domElement)
    
    // 创建光源 - 暂时注释掉
    // createLights(THREE)
    
    // 创建太阳
    createSun(THREE)
    
    // 创建行星和轨道
    createPlanets(THREE)
    
    // 通知组件已准备就绪
    emit('ready', { scene, camera, renderer })
    
  } catch (error) {
    console.error('SolarSystem initialization failed:', error)
    emit('error', error)
  }
}

// 创建光源 - 暂时注释掉，保持行星黑色
// const createLights = (THREE) => {
//   // 环境光 - 增强亮度
//   const ambientLight = new THREE.AmbientLight(0xffffff, 0.8)
//   scene.add(ambientLight)
//   
//   // 点光源（太阳光） - 增强强度
//   const sunLight = new THREE.PointLight(0xffffff, 1.5, 100)
//   sunLight.position.set(0, 0, 0)
//   scene.add(sunLight)
// }

// 创建太阳
const createSun = (THREE) => {
  const sunGeometry = new THREE.SphereGeometry(1.8, 32, 32)
  const sunMaterial = new THREE.MeshBasicMaterial({ 
    color: 0xFFB347, // 稍微偏橙色的金黄色
    emissive: 0xFFB347, // 发光色为偏橙色
    emissiveIntensity: 0.3 // 适中的发光强度
  })
  sun = new THREE.Mesh(sunGeometry, sunMaterial)
  scene.add(sun)
}

// 创建行星和轨道
const createPlanets = (THREE) => {
  planetData.forEach((data) => {
    // 创建轨道
    const orbitGeometry = new THREE.RingGeometry(data.distance - 0.15, data.distance + 0.15, 64)
    const orbitMaterial = new THREE.MeshBasicMaterial({ 
      color: 0x8B8B8B, // 更亮的灰色
      side: THREE.DoubleSide,
      transparent: true,
      opacity: 0.3 // 降低透明度，让轨道更微妙
    })
    const orbit = new THREE.Mesh(orbitGeometry, orbitMaterial)
    orbit.rotation.x = Math.PI / 2
    scene.add(orbit)
    
    // 创建行星
    const planetGeometry = new THREE.SphereGeometry(data.size, 16, 16)
    const planetMaterial = new THREE.MeshBasicMaterial({ 
      color: 0x000000, // 黑色行星
      transparent: false,
      opacity: 1.0
    })
    const planet = new THREE.Mesh(planetGeometry, planetMaterial)
    
    // 设置行星初始位置
    planet.position.x = data.distance
    planet.position.y = 0
    planet.position.z = 0
    planet.rotation.z = data.tilt
    
    // 存储行星信息
    planet.userData = {
      distance: data.distance,
      speed: data.speed,
      angle: Math.random() * Math.PI * 2,
      name: data.name
    }
    
    planets.push(planet)
    scene.add(planet)
  })
}

// 动画循环
const animate = () => {
  if (!props.enableAnimation) return
  
  animationId = requestAnimationFrame(animate)
  
  // 太阳自转
  if (sun) sun.rotation.y += 0.005
  
  // 行星公转
  planets.forEach(planet => {
    const data = planet.userData
    data.angle += data.speed
    
    planet.position.x = Math.cos(data.angle) * data.distance
    planet.position.z = Math.sin(data.angle) * data.distance
    
    // 行星自转
    planet.rotation.y += 0.01
  })
  
  if (renderer && scene && camera) {
    renderer.render(scene, camera)
  }
}

// 响应式调整渲染器尺寸
const resizeRenderer = () => {
  if (camera && renderer && container.value) {
    const containerRect = container.value.getBoundingClientRect()
    const width = Math.min(containerRect.width, props.size)
    const height = Math.min(containerRect.height, props.size)
    
    camera.aspect = width / height
    camera.updateProjectionMatrix()
    renderer.setSize(width, height)
  }
}

// 清理资源
const cleanup = () => {
  if (animationId) {
    cancelAnimationFrame(animationId)
    animationId = null
  }
  
  if (renderer) {
    renderer.dispose()
    renderer = null
  }
  
  // 清理场景
  if (scene) {
    scene.clear()
    scene = null
  }
  
  // 重置变量
  camera = null
  sun = null
  planets = []
}

// 生命周期
onMounted(() => {
  if (process.client) {
    // 加载设置
    loadSettings()
    
    // 只有当设置启用时才初始化
    if (isVisible.value) {
      initThreeJS()
      if (props.enableAnimation) {
        animate()
      }
      window.addEventListener('resize', resizeRenderer)
    }
  }
})

// 加载设置
const loadSettings = () => {
  if (process.client) {
    try {
      const savedSettings = localStorage.getItem('solarSystemSettings')
      if (savedSettings) {
        solarSystemSettings.value = { ...solarSystemSettings.value, ...JSON.parse(savedSettings) }
      }
    } catch (error) {
      console.error('加载太阳系设置失败:', error)
    }
  }
}

onUnmounted(() => {
  if (process.client) {
    window.removeEventListener('resize', resizeRenderer)
    cleanup()
  }
})

// 暴露方法供父组件调用
defineExpose({
  // 手动显示/隐藏
  show: () => { isVisible.value = true },
  hide: () => { isVisible.value = false },
  // 重新初始化
  reinit: () => {
    cleanup()
    initThreeJS()
    if (props.enableAnimation) {
      animate()
    }
  },
  // 获取状态
  getStatus: () => ({
    visible: isVisible.value,
    scene: !!scene,
    camera: !!camera,
    renderer: !!renderer
  })
})
</script>

<style scoped>
.solar-system-container {
  width: 80px;
  height: 80px;
  margin-top: -20px;
  margin-bottom: -20px;
  margin-left: 8px; /* 向右移动8px，与标题拉开距离 */
  position: relative;
  overflow: hidden;
  /* 确保不影响主体布局 */
  flex-shrink: 0;
  pointer-events: none; /* 不响应鼠标事件，纯装饰 */
}

.solar-system-container canvas {
  width: 100% !important;
  height: 100% !important;
  display: block;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .solar-system-container {
    width: 60px;
    height: 60px;
    margin-top: -15px;
    margin-bottom: -15px;
  }
}

@media (max-width: 480px) {
  .solar-system-container {
    width: 50px;
    height: 50px;
    margin-top: -10px;
    margin-bottom: -10px;
  }
}
</style>
